//
//  CourseDetailViewController.m
//  Civacrm
//
//  Created by 王桂敏 on 2017/2/9.
//  Copyright © 2017年 王桂敏. All rights reserved.
//

#import "CourseDetailViewController.h"
#import "WKDelegateController.h"
#import "UpdateImageViewController.h"
#import "PreviewViewController.h"
#import "LoadingView.h"
#import "PlayerViewController.h"

static NSString *const JavascriptReportPhoto  = @"photo";   //js交互
@interface CourseDetailViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate,WKDelegate>

@property (nonatomic,strong) WKWebView *wkWebView;

@property (nonatomic,strong) LoadingView *loading;

@end

@implementation CourseDetailViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setNavigationBarTransparent:YES];
    [self.navigationController.navigationBar setHidden:YES];
    self.edgesForExtendedLayout = UIRectEdgeTop;
  
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setNavigationBarTransparent:NO];
    
    [self handleNotificationEnterForegroundAction:nil];
    
}


- (void)loadExamplePage:(WKWebView*)webView {
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [webView loadHTMLString:appHtml baseURL:baseURL];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNotification];
    [self initView];
    
}

#pragma mark - init
- (void)initNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotificationEnterForegroundAction:)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
}
-(void)initView {
    self.view.backgroundColor = ClearColor;
    [self.view addSubview:self.wkWebView];
    self.webURL = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self.webURL, nil, nil, kCFStringEncodingUTF8));
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.webURL]];
    [self.wkWebView loadRequest:req];
   
    [self.view addSubview:self.loading];
    
}

- (LoadingView *)loading{
    if (!_loading) {
        self.loading = [[LoadingView alloc] initWithFrame:CGRectZero];
    }
    return _loading;
}

- (WKWebView *)wkWebView
{
    if (!_wkWebView) {
        
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 0;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        
        // 通过JS与webview内容交互
        userContentController =[[WKUserContentController alloc]init];
        config.userContentController = userContentController;
        [config.userContentController addScriptMessageHandler:self name:JavascriptReportPhoto];
        
        self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds
                                            configuration:config];
        //注册方法
        WKDelegateController * delegateController = [[WKDelegateController alloc]init];
        delegateController.delegate = self;
        // 导航代理
        _wkWebView.navigationDelegate = self;
        // 与webview UI交互代理
        _wkWebView.UIDelegate = self;
        
        
    }
    return _wkWebView;
}
#pragma mark - NotificationAction -
- (void)handleNotificationEnterForegroundAction:(NSNotification *)sender{
    //方法一
//    [self.wkWebView evaluateJavaScript:@"window.location.href ='about:blank';" completionHandler:nil];
    //方法二
    NSString *js = @"audioPause()";
    [self.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"response: %@ error: %@", response, error);
        NSLog(@"call js alert by native");
    }];
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:JavascriptReportPhoto]) {
        // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,
        // NSDictionary, and NSNull类型
        NSLog(@"%@", message.body);
        

        if ([message.body[@"method"] isEqualToString:@"uploadPhoto"]) {

            UpdateImageViewController *VC = [[UpdateImageViewController alloc] init];
            VC.model = self.model;
            VC.subTaskId = message.body[@"subTaskId"];
            VC.taskType = message.body[@"taskType"];
            @weakify(self);
            VC.block = ^(){
                @strongify(self);

                NSString *js = @"updataState()";
                [self.self.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                    NSLog(@"response: %@ error: %@", response, error);
                }];
            };
            [self.navigationController pushViewController:VC animated:YES];
        }
        if ([message.body[@"method"] isEqualToString:@"previewPhoto"]) {
            
            PreviewViewController *VC = [[PreviewViewController alloc] init];
            VC.model = self.model;
            VC.subTaskId = message.body[@"subTaskId"];
            
            [self.navigationController pushViewController:VC animated:YES];
        }
        if ([message.body[@"method"] isEqualToString:@"goBack"]) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        if ([message.body[@"method"] isEqualToString:@"play"]) {
            if (self.netState == AFNetworkReachabilityStatusReachableViaWWAN || self.netState == AFNetworkReachabilityStatusUnknown) {
                @weakify(self);
                [self showAlertWithTitle:@"提示" message:@"移动网络环境下观看视频将会消耗大量流量，您要继续吗" actionNameArray:@[@"取消播放",@"去播放"] action:^(NSInteger index) {
                    @strongify(self);
                    switch (index) {
                        case 0:
                        {
                            
                        }
                            break;
                        case 1:
                        {
                            
                            AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                            appDelegate.allowRotation = YES;
                            SEL selector = NSSelectorFromString(@"setOrientation:");
                            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
                            [invocation setSelector:selector];
                            [invocation setTarget:[UIDevice currentDevice]];
                            int val = UIInterfaceOrientationLandscapeRight;
                            [invocation setArgument:&val atIndex:2];
                            [invocation invoke];
                            PlayerViewController *VC = [[PlayerViewController alloc] init];
                            VC.playUrl = message.body[@"url"];
                            [self.navigationController pushViewController:VC animated:YES];
                        }
                            break;
                            
                        default:
                            break;
                    }
                } VC:self];
            } else {
                PlayerViewController *VC = [[PlayerViewController alloc] init];
                VC.playUrl = message.body[@"url"];
                AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                appDelegate.allowRotation = YES;
                SEL selector = NSSelectorFromString(@"setOrientation:");
                NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
                [invocation setSelector:selector];
                [invocation setTarget:[UIDevice currentDevice]];
                int val = UIInterfaceOrientationLandscapeRight;
                [invocation setArgument:&val atIndex:2];
                [invocation invoke];
                [self.navigationController pushViewController:VC animated:YES];
            }
            
            
        }
        
    }
}

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    
    NSLog(@"开始调用");
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
    NSLog(@"开始返回");
}

// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self.loading removeFromSuperview];
    self.loading = nil;
    NSLog(@"加载完成");
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [self hideHud];
    NSLog(@"加载失败");
    
}


- (void)dealloc{
    [userContentController removeScriptMessageHandlerForName:JavascriptReportPhoto];
    [self removeObserver:self];

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
